import { useEffect, useState } from 'react';
import { useUpdate } from './useUpdate';
import { Toast } from 'antd-mobile';

export type RecordItem = {
  tagIds: number[];
  note: string;
  category: '-' | '+';
  amount: number;
  createdAt: string; // ISO-8601
};

// 去掉 createAt 属性
type NewRecordItem = Omit<RecordItem, 'createdAt'>;

export const useRecords = () => {
  const [records, setRecords] = useState<RecordItem[]>([]);

  useEffect(() => {
    setRecords(JSON.parse(window.localStorage.getItem('records') || '[]'));
  }, []);

  useUpdate(() => {
    window.localStorage.setItem('records', JSON.stringify(records));
  }, records);

  const addRecord = (newRecord: NewRecordItem) => {
    if (newRecord.amount <= 0) {
      Toast.info('请输入金额', 2);
      return false;
    }
    if (newRecord.tagIds.length === 0) {
      Toast.info('请选择标签', 2);
      return false;
    }
    const record = { ...newRecord, createdAt: new Date().toISOString() };
    setRecords([...records, record]);
    return true;
  };

  return { records, addRecord };
};
